package com.example.client;

import com.example.model.DeviceType;
import com.example.service.Tenant;
import lombok.extern.slf4j.Slf4j;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * 使用jdbc thin client
 */
@Slf4j
public class DeviceClientService {

    private Tenant tenant;

    private DataSource dataSource;

    public void setTenant(Tenant tenant) {
        this.tenant = tenant;
    }

    public Tenant getTenant() {
        return tenant;
    }

    public DataSource getDataSource() {
        return dataSource;
    }

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    private String getDeviceCacheName() {
        return "SQL_" + tenant.name() + "_DEVICE";
    }

    private String getDeviceTypeCacheName() {
        return "SQL_" + tenant.name() + "_DEVICE_TYPE";
    }

    private String getSchemaPrefix() {
        return tenant.getSchema() + ".";
    }

    public void saveDeviceType(DeviceType deviceType) throws SQLException {
        String sql="INSERT INTO " + getSchemaPrefix() + "DEVICETYPE(id,name,description,active) values(?,?,?,?)";
        try (Connection conn=dataSource.getConnection()){
            PreparedStatement statement= conn.prepareStatement(sql);
            statement.setLong(1,deviceType.getId());
            statement.setString(2,deviceType.getName());
            statement.setString(3,deviceType.getDescription());
            statement.setBoolean(4,deviceType.getActive());
            int count=statement.executeUpdate();
            log.info("Update {} records",count);
        }catch (Exception e){
            log.error("ERROR insert device type with thin client",e);
            throw new RuntimeException("ERROR insert device type with thin client",e);
        }


    }
}
